package com.imooc.controller;

import com.imooc.common.enums.ResultEnum;
import com.imooc.common.form.CategoryForm;
import com.imooc.dataobject.ProductCategory;
import com.imooc.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    CategoryService categoryService;

    /**
     * 类目列表
     *
     * @return
     */
    @RequestMapping("/list")
    public ModelAndView list() {
        Map<String, Object> params = new HashMap<>();
        List<ProductCategory> categoryList = categoryService.findAll();
        params.put("categoryList", categoryList);
        return new ModelAndView("category/list", params);
    }

    /**
     * 展示
     *
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index(@RequestParam(value = "categoryId", required = false) Integer categoryId) {
        Map<String, Object> params = new HashMap<>();
        if (categoryId != null) {
            ProductCategory category = categoryService.findOne(categoryId);
            params.put("category", category);
        }

        return new ModelAndView("category/index", params);
    }

    /**
     * 新增/修改 提交保存
     *
     * @param categoryForm
     * @return
     */
    @RequestMapping("/save")
    public ModelAndView save(CategoryForm categoryForm) {
        Map<String, Object> params = new HashMap();
        log.info("categoryForm = {}", categoryForm);
        try {
            ProductCategory category = new ProductCategory();
            if (categoryForm.getCategoryId() != null) {
                category = categoryService.findOne(categoryForm.getCategoryId());
            }
            BeanUtils.copyProperties(categoryForm, category);
            categoryService.save(category);
        } catch (Exception e) {
            params.put("msg", e.getMessage());
            params.put("url", "/sell/seller/category/index");
            return new ModelAndView("common/error", params);
        }

        params.put("msg", ResultEnum.SUCCESS.getMessage());
        params.put("url", "/sell/seller/category/list");
        return new ModelAndView("common/success", params);
    }
}
